﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using mqtttLib;
using mqtttLib.Helper;
using mqtttLib.Messages.Base;
using Server.Helper;
using Server.Model;

namespace Server
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 通信服务
        /// </summary>
        private MqttServer _communServer;

        private void Form2_Load(object sender, EventArgs e)
        {
            txtPort.Text = ConfigureAppConfig.GetConnectionStringsValue("Port");
            ip_txt.Text = ConfigureAppConfig.GetConnectionStringsValue("Ip");
            btnStart_Click(null, null);
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                int port;
                if (!int.TryParse(txtPort.Text, out port))
                {
                    MessageBox.Show(@"输入值不是合法的数字", @"错误");
                    return;
                }
                var dd = new LogInfo("log4net.config", "");
                //通信服务
                _communServer = new MqttServer(port, dd);
                _communServer.LogEvent += _communServer_LogEvent;
                _communServer.ConnectValidatEvent += _communServer_ConnectValidatEvent;
                _communServer.Start();
                btnStart.Enabled = false;
                btnStop.Enabled = true;
            }
            catch (Exception)
            {
                //  ILog log = LogFactory.GetLogger("Main");
                //  log.Debug(ex);

            }
        }

        private bool _communServer_ConnectValidatEvent(string userName, string password)
        {
            return true;
        }

        private void _communServer_LogEvent(string title, MqttMessage data)
        {
            if (ckbShow.Checked)
            {
                //if (!(data is PublishMessage))
                {
                    if (txtInfo.InvokeRequired)
                    {
                        //后端线程向主线程记日志
                        Invoke(new Action<string, MqttMessage>(_communServer_LogEvent), title, data);
                    }
                    else
                    {
                        //主线程直接记日志

                        if (ckbHex.Checked)
                        {
                            // ReSharper disable once LocalizableElement
                            txtInfo.Text += title + data.GetDataBytes().GetHexLog() + "\r\n";
                        }
                        else
                        {
                            // ReSharper disable once LocalizableElement
                            txtInfo.Text += title + data.ToJson() + "\r\n";
                        }
                    }
                }
            }

        }



        //private void _communServer_LogEvent(string title, byte[] data)
        //{
        //    if (ckbShow.Checked)
        //    {
        //        //if (ckbHex.Checked)
        //        //{

        //        //}
        //        if (txtInfo.InvokeRequired)
        //        {
        //            //后端线程向主线程记日志
        //            Invoke(new Action<string, byte[]>(_communServer_LogEvent), title, data);
        //        }
        //        else
        //        {
        //            //主线程直接记日志
        //            txtInfo.Text += title + data.GetHexLog() + "\r\n";
        //        }
        //    } 
        //} 

        /// <summary>
        /// 停止监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_communServer != null)
            {
                _communServer.Stop();
                _communServer = null;
            }

            btnStop.Enabled = false;
            btnStart.Enabled = true;
        }


        /// <summary>
        /// 清除消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtInfo.Text = "";
        }
        private void button1_Click(object sender, EventArgs e)
        {

            //HeartbeatResult signInResult = new HeartbeatResult(filePath, EquipmentId, CommunTypeEnum.ServerResponse, 1);
            //_communServer.SendAll(signInResult);
        }

        private void Config_MenuItem_Click(object sender, EventArgs e)
        {
            SetStation form2 = new SetStation();
            form2.UpdateEvent += () =>
            {
                ip_txt.Text = ConfigureAppConfig.GetConnectionStringsValue("Ip");
                txtPort.Text = ConfigureAppConfig.GetConnectionStringsValue("Port");
                btnStop_Click(null, null);
            };
            form2.Show();
        }


        private void ClientMenuItem_Click(object sender, EventArgs e)
        {
            var d = _communServer.Session.Values1;
            List<Client> models = d.Select(item => new Client()
            {
                ClientId = item.Key,
                Address = item.Value.V.Address.ToString()
            }).ToList();
            ClientShowForm client = new ClientShowForm(models);
            client.RestartEvent += clientId =>
            {
                _communServer.SendRestart(clientId);
                List<Client> mod = d.Select(item => new Client()
                {
                    ClientId = item.Key,
                    Address = item.Value.V.Address.ToString()
                }).ToList();
                client.ShowData(mod);
                //  btnStop_Click(null, null);
            };
            client.Show();
        }



        private void TopicMenuItem_Click(object sender, EventArgs e)
        {
            List<Topic> models = new List<Topic>();

            foreach (var item in _communServer.Topic)
            {
                var model = new Topic()
                {
                    TopicName = item.Key,
                    Count = item.Value.Count,
                    ClientS = new LinkedList<Client>()
                };

                foreach (var i in item.Value)
                {
                    model.ClientS.AddLast(new Client() { ClientId = i.Info.ClientId, Address = i.Address.ToString() });
                }
                models.Add(model);
            }
            TopicShowForm topicShowForm = new TopicShowForm(models);

            topicShowForm.Show();
        }
    }
}
